<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\common\model\Help;
use app\common\model\Member;
use app\common\model\MobileCode;
use app\validate\Check;
use library\Controller;
use think\Db;
use think\Request;
use app\common\controller\Wxpay;
use app\common\controller\Wxpay2;
use app\common\model\Wechat;
use think\swoole\Server;
use phpcode\QrCode;

class Index extends Base
{
    public function index()
    {
        return '0';
    }

    //验证码发送
    public function sms_code(MobileCode $mobileCode, Request $request, Check $check)
    {
        try {
            $param = $request->param();
            $result = $check->scene('mobile_check')->check($param);
            if (!$result) {
                return $this->api_result(400, $check->getError(), []);
            } else {
                if ($this->isValidMobileNumber($param['mobile'])) {
                    $code = $mobileCode->code($param);
                    if ($code) {
                        $param['code'] = $code;
                        return $this->api_result(200, '提交成功', $param);
                    } else {
                        return $this->api_result(400, '请不要重复提交', $param);
                    }
                } else {
                    return $this->api_result(400, '手机号格式错误', []);
                }
            }
        } catch (\Exception $e) {
            return $this->api_result(400, '提交失败', []);
        }
    }

    //手机号注册
    public function register(Member $member, Request $request, Check $check)
    {
        try {
            $param = $request->param();
            $result = $check->scene('mobile_register')->check($param);
            if (!$result) {
                return $this->api_result(400, $check->getError(), []);
            } else {
                if ($this->isValidMobileNumber($param['mobile'])) {
                    $user = $member->register($param);
                    if ($user) {
                        if ($user == 1) {
                            $param['user'] = $member::where(['phone' => $param['mobile']])->find();
                            return $this->api_result(200, '注册成功', $param);
                        } elseif ($user == 2) {
                            return $this->api_result(400, '实名认证未通过', $param);
                        } else {
                            return $this->api_result(400, '提交失败!', []);
                        }
                    } else {
                        return $this->api_result(400, '请不要重复提交', $param);
                    }
                } else {
                    return $this->api_result(400, '手机号格式错误', []);
                }
            }
        } catch (\Exception $e) {
            return $this->api_result(400, '提交失败', []);
        }
    }

    //登录
    public function login(Member $member, Request $request, Check $check)
    {
        try {
            $param = $request->param();
            $result = $check->scene('login_check')->check($param);
            if (!$result) {
                return $this->api_result(400, $check->getError(), []);
            } else {
                if ($this->isValidMobileNumber($param['mobile'])) {
                    $msg = $member->login($param);
                    if ($msg == 1) {
                        $param['user'] = $member::where(['phone' => $param['mobile']])->find();
                        return $this->api_result(200, '登录成功', $param);
                    } else {
                        return $this->api_result(400, $msg, $param);
                    }
                } else {
                    return $this->api_result(400, '手机号格式错误', []);
                }
            }
        } catch (\Exception $e) {
            return $this->api_result(400, '登录失败', []);
        }
    }

    //微信授权登录
    public function wx_login(Member $member, Request $request, Check $check)
    {
        try {
            $param = $request->param();
            $result = $check->scene('wx_login_check')->check($param);
            if (!$result) {
                return $this->api_result(400, $check->getError(), []);
            } else {
                $msg = $member->wx_login($param);
                if ($msg == 1) {
                    $param['user'] = $member::where(['openid' => $param['openid']])->find();
                    return $this->api_result(200, '登录成功', $param);
                } else {
                    return $this->api_result(400, $msg, $param);
                }
            }
        } catch (\Exception $e) {
            return $this->api_result(400, '登录失败', []);
        }
    }


    //文本
    public function getList()
    {
        $id = input("id");
        $type = input("type") ?? '';
        if (empty($type)) {
            $data = Db::table("system_banner")->field("id,title,logo,content")->where("id=$id")->find();
        } else {
            if ($type == 'youhui') {
                $data = Db::table("store_state")->field("id,title,content")->where("id=83338081684615")->find();
            }
            if ($type == 'activity') {
                $data = Db::table("store_state")->field("id,title,content")->where("id=83338081684616")->find();
            }
            if ($type == 'vip') {
                $data = Db::table("store_state")->field("id,title,content")->where("id=83338081684617")->find();
            }
            if ($type == 'message') {
                $data = Db::table("store_state")->field("id,title,content")->where("id=$id")->find();
            }
        }

        return $this->api_result(200, '请求成功', $data);
    }


    //基础配置
    public function basic()
    {
        $index_bg = Db::table("system_banner")->field("id,title,logo,content")->where("cate_id=1 and status=1")->find();
        $index_pop = Db::table("system_banner")->field("id,title,logo,content")->where("cate_id=2 and status=1")->select();

        $login_banner = Db::table("system_banner")->field("id,title,logo,content")->where("cate_id=3 and status=1")->select();

        $index_banner = Db::table("system_banner")->field("id,title,logo,content")->where("cate_id=4 and status=1")->select();

        $privacy = Db::table("store_state")->field("id,title,content")->where("title='使用协议'")->find();
        $agreement = Db::table("store_state")->field("id,title,content")->where("title='隐私政策'")->find();
        $hezuo = Db::table("store_state")->field("id,title,content")->where("title='合作协议'")->find();


        $xinshou = Db::table("store_state")->field("id,title,content")->where("title='新手指南'")->find();
        $caozuo = Db::table("store_state")->field("id,title,content")->where("title='操作说明'")->find();

        $data = ['index_bg' => $index_bg, 'index_pop' => $index_pop, 'login_banner' => $login_banner, 'index_banner' => $index_banner, 'hezuo' => $hezuo, 'privacy' => $privacy, 'xinshou' => $xinshou, 'caozuo' => $caozuo, 'agreement' => $agreement];
        return $this->api_result(200, '请求成功', $data);
    }

    //消息盒子
    public function message_list()
    {
        $data = Db::table("store_state")->field("id,title,content")->where("cate_id='2'")->select();
        return $this->api_result(200, '请求成功', $data);
    }


    //修改昵称头像
    public function edit_user()
    {
        $user_id = input("user_id") ?? '';

        $headimg = input("headimg") ?? '';
        $nickname = input("nickname") ?? '';
        $username = input("username") ?? '';
        $phone = input("phone") ?? '';

        $wechat_number = input("wechat_number") ?? '';
        $wechat_phone = input("wechat_phone") ?? '';
        $wechat_pic = input("wechat_pic") ?? '';

        $alipay_number = input("alipay_number") ?? '';
        $alipay_phone = input("alipay_phone") ?? '';
        $alipay_pic = input("alipay_pic") ?? '';

        $bank_number = input("bank_number") ?? '';
        $bank_name = input("bank_name") ?? '';
        $bank_address = input("bank_address") ?? '';

        $d = [];

        if ($headimg) {
            $d['headimg'] = $headimg;
        }
        if ($nickname) {
            $d['nickname'] = $nickname;
        }
        if ($username) {
            $d['username'] = $username;
        }
        if ($phone) {
            $d['phone'] = $phone;
        }

        if ($wechat_number) {
            $d['wechat_number'] = $wechat_number;
        }
        if ($wechat_phone) {
            $d['wechat_phone'] = $wechat_phone;
        }
        if ($wechat_pic) {
            $d['wechat_pic'] = $wechat_pic;
        }

        if ($alipay_number) {
            $d['alipay_number'] = $alipay_number;
        }
        if ($alipay_phone) {
            $d['alipay_phone'] = $alipay_phone;
        }
        if ($alipay_pic) {
            $d['alipay_pic'] = $alipay_pic;
        }

        if ($bank_number) {
            $d['bank_number'] = $bank_number;
        }
        if ($bank_name) {
            $d['bank_name'] = $bank_name;
        }
        if ($bank_address) {
            $d['bank_address'] = $bank_address;
        }

        if (count($d)) {
            Db::table("store_member")->where("id='$user_id'")->update($d);
        }

        return $this->api_result(200, '请求成功', []);
    }

    //上传图片
    public function uploads($path = "static/uploads/")
    {
        $help = new Help();

        $filename = 'file';
        $pic_path = '';
        $picname = $_FILES[$filename]['name'];
        $picsize = $_FILES[$filename]['size'];
        if ($picname != "") {
            $type = $help->getSuffix($picname);
            if ($type != 'jpg' && $type != 'gif' && $type != 'png' && $type != 'jpeg' && $type != 'JPG' && $type != 'PNG' && $type != 'JPEG') {
                $array = array(
                    'name' => '格式错误,请上传jpg,gif,png,jpeg',
                    'pic' => '',
                    'size' => '',
                    'pic_path' => ''
                );
                return json_encode($array);
            }
            $type = '.' . $type;
            $md5 = md5(uniqid());
            $pics = $md5 . $type;
            $path = $help->create_dir($path);
            $pic_path = strtr($path, array('./' => '')) . $pics;
            move_uploaded_file($_FILES[$filename]['tmp_name'], $pic_path);
        }

        $shuxing = @getimagesize($pic_path);
        if (!empty($shuxing)) {
            $width = (int)$shuxing[0];
            $height = (int)$shuxing[1];
            $w = 750;
            $h = 750 * $height / $width;
        } else {
            $w = $h = 750;
        }

        if (file_exists($pic_path)) {
            $image_small = $help->resize_image($pic_path, $path, $w, $h);
        } else {
            $image_small = $pic_path;
        }

        $size = round($picsize / 1024, 2);
        $arr = array(
            'name' => $picname,
            'pic' => $pic_path,
            'small_pic' => $image_small,
            'size' => $size,
            'pic_path' => sysconf('realm_name') . '/' . $pic_path,
            'pic_small' => sysconf('realm_name') . '/' . $image_small
        );
        return $this->api_result(200, '请求成功', $arr);
    }

    //二维码测试路径
    public function device()
    {
        echo input('No');
    }

    //回复报文
    public function bao_wen()
    {
        $send_data = "680C000000012024122014523300DA4C";
        $buffer = json_encode($send_data) . "\n";
        $client = stream_socket_client('tcp://localhost:9004');
        fwrite($client, $buffer);
    }

    // 获取微信小程序用户openid和session_key
    public function getOpenid(Wechat $wechat, Request $request, Help $help)
    {
        $wx_config = $wechat->mini_config();
        $code = $_POST['code'];                            //小程序传来的code值
        $appid = $wx_config['app_id'];                        //小程序的appid
        $appSecret = $wx_config['app_secret'];                //小程序的$appSecret
        $wxUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appSecret&js_code=$code&grant_type=authorization_code";
        $result = $help->curl_request($wxUrl);//请求拼接好的url
        if ($result) {
            return $this->api_result(200, '请求成功', json_decode($result, true));
        } else {
            return $this->api_result(400, '请求失败', []);
        }
    }


    //token
    public function token()
    {
        $wechat = new Wechat();
        $token = Db::table("yz_access_token")->where("id=1")->find();
        if ($token) {
            $time1 = strtotime($token['time']);
            $time2 = time();
            $cha = $time2 - $time1;
            if ($cha > 3600) {
                $wx_config = $wechat->mini_config();
                $appid = $wx_config['app_id'];                        //小程序的appid
                $appSecret = $wx_config['app_secret'];                //小程序的$appSecret
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appSecret";
                $result = $this->http_request($url);
                $access_token = json_decode($result)->access_token;
                Db::table("yz_access_token")->where("id=1")->update(['access_token' => $access_token, 'time' => date('Y-m-d H:i:s')]);
                return $this->api_result(200, '请求成功', $access_token);
            } else {
                return $this->api_result(200, '请求成功', $token['access_token']);
            }
        } else {
            $wx_config = $wechat->mini_config();
            $appid = $wx_config['app_id'];                        //小程序的appid
            $appSecret = $wx_config['app_secret'];                //小程序的$appSecret
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appSecret";
            $result = $this->http_request($url);
            $access_token = json_decode($result)->access_token;
            return $this->api_result(200, '请求成功', $access_token);
        }
    }

    //token
    public function token2()
    {
        $wechat = new Wechat();
        $token = Db::table("yz_access_token")->where("id=1")->find();
        if ($token) {
            $time1 = strtotime($token['time']);
            $time2 = time();
            $cha = $time2 - $time1;
            if ($cha > 3600) {
                $wx_config = $wechat->mini_config();
                $appid = $wx_config['app_id'];                        //小程序的appid
                $appSecret = $wx_config['app_secret'];                //小程序的$appSecret
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appSecret";
                $result = $this->http_request($url);
                $access_token = json_decode($result)->access_token;
                Db::table("yz_access_token")->where("id=1")->update(['access_token' => $access_token, 'time' => date('Y-m-d H:i:s')]);
                return $access_token;
            } else {
                return $token['access_token'];
            }
        } else {
            $wx_config = $wechat->mini_config();
            $appid = $wx_config['app_id'];                        //小程序的appid
            $appSecret = $wx_config['app_secret'];                //小程序的$appSecret
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appSecret";
            $result = $this->http_request($url);
            $access_token = json_decode($result)->access_token;
            return $access_token;
        }
    }


    //http_request
    public function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    //充值
    public function charge(Member $member, Request $request, Check $check)
    {
        try {
            $param = $request->param();
            $result = $check->scene('charge')->check($param);
            if (!$result) {
                return $this->api_result(400, $check->getError(), []);
            } else {
                $data = $member->charge($param);
                if ($data) {
                    $wechat = new Wechat();
                    $_W = $wechat->mini_config();

                    Db::startTrans();

                    $user = $member::where(["id" => $param['user_id']])->find();

                    $body = '微信支付';

                    $appid = $_W['app_id'];
                    $openid = $user['openid']; //oQKgL0ZKHwzAY-KhiyEEAsakW5Zg
                    $mch_id = $_W['mchid'];
                    $key = $_W['mchkey'];
                    $out_trade_no = $data['out_trade_no'];
                    $total_fee = $data['amount'];
                    $root = sysconf('realm_name') . '/index.php/api/index/wechat_notify';

                    if (empty($total_fee)) //押金
                    {
                        $total_fee = floatval(99 * 100);
                    } else {
                        $total_fee = floatval($total_fee * 100);
                    }

                    //$total_fee = 1;


                    $weixinpay = new Wxpay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee, $root);
                    $return = $weixinpay->pay();
                    Db::commit();

                    return $this->api_result(200, '请求成功', $return);
                }
            }
        } catch (\Exception $e) {
            return $this->api_result(400, '请求失败', []);
        }
    }


    //微信回调
    public function wechat_notify()
    {
        $help = new Help();

        $xml = file_get_contents('php://input');
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        file_put_contents('log.txt', $arr, FILE_APPEND);
        if ($arr) {
            if ($arr['result_code'] == 'SUCCESS') {
                $out_trade_no = trim($arr['out_trade_no']);

                $find = Db::table("store_member_amount_log")->where(array('out_trade_no' => $out_trade_no))->find();
                if ($find) {
                    $user_id = $find['user_id'];
                    $money = $find['amount'];
                    Db::table('store_member_amount_log')->where(array('out_trade_no' => $out_trade_no))->update(['is_pay' => 1, 'pay_time' => date('Y-m-d H:i:s')]);
                    Db::query("update store_member set amount=amount+$money where id=$user_id");
                }
            }
        }

        $return = array('return_code' => 'SUCCESS', 'return_msg' => 'OK');
        $xml = '<xml>';
        foreach ($return as $k => $v) {
            $xml .= '<' . $k . '><![CDATA[' . $v . ']]></' . $k . '>';
        }
        $xml .= '</xml>';

        echo $xml;
        exit;
    }

    //测试ascii
    public function change_ascii()
    {
        $hexString = "68747470733A2f2f6170702E79696E756F78696E6E656E677975616E2E636E2F696E6465782E7068702F6170692F696E6465782F6465766963653f4e6f3d";
        echo $this->hexToAscii($hexString);
    }

    //hex转Ascii
    public function hexToAscii($hexString)
    {
        $asciiString = '';
        for ($i = 0; $i < strlen($hexString); $i += 2) {
            $asciiString .= pack('H*', substr($hexString, $i, 2));
        }
        return $asciiString;
    }


    //随机订单号
    public function order_sn()
    {
        return date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    //开启充电
    public function start_charge()
    {
        $device_sn = input('device_sn') ?? '20250113174834';

        $order_no = input('order_no') ?? $this->order_sn();
        $order_no = $order_no . '0';

        $find = Db::table("dev")->where(['device_sn' => $device_sn])->order("id desc")->limit(1)->find();
        if($find){

            $connect = $find['connect'];

            $baowen = "680D00000099" . $device_sn . $order_no . '000000000100358f'.$connect.'200358f6666777788889999';
            $baowen_res = str_split($baowen, 2);

            $answer = '';
            foreach ($baowen_res as $k => &$v) {
                $answer .= chr(intval('0x' . $v, 16));
            }
            $buffer = $answer;
            $client = stream_socket_client('tcp://localhost:9003');
            fwrite($client, $buffer);
        }

    }


    //关闭充电
    public function close_charge()
    {
        $device_sn = input('device_sn') ?? '20250113174834';

        $find = Db::table("dev")->where(['device_sn' => $device_sn])->order("id desc")->limit(1)->find();
        if($find){

            $connect = $find['connect'];

            $baowen = "680D00000098" . $device_sn . "0100358f".$connect.'200358f6666777788889999';
            $baowen_res = str_split($baowen, 2);

            $answer = '';
            foreach ($baowen_res as $k => &$v) {
                $answer .= chr(intval('0x' . $v, 16));
            }
            $buffer = $answer;
            $client = stream_socket_client('tcp://localhost:9003');
            fwrite($client, $buffer);
        }

    }

    //测试序列号订单号
    public function cs()
    {
        $order = "00000000000001737367808733860486";
        echo str_replace("0000000000000", "", $order);
    }

    //测试序列号报文
    public function test()
    {
        $str = "0f000013000000000000017373639039903882832025011317483401030201d3089b00000000000000000000000002000000a2030000a2030000d00700000000";
        $res = str_split($str, 2);

        $out_trade_no = $res[4] . $res[5] . $res[6] . $res[7] . $res[8] . $res[9] . $res[10] . $res[11] . $res[12] . $res[13] . $res[14] . $res[15] . $res[16] . $res[17] . $res[18] . $res[19];
        //print_r('订单号：' . $out_trade_no);
        //print_r(PHP_EOL);
        $device = $res[20] . $res[21] . $res[22] . $res[23] . $res[24] . $res[25] . $res[26];
        //print_r('设备号：' . $device);
        //print_r(PHP_EOL);
        $qiang = $res[27];
        //print_r('枪号：' . $qiang);
        $status = $res[28];
        //print_r('状态：' . $status);
        $guiwei = $res[29];
        //print_r('是否归位：' . $guiwei);
        $chaqiang = $res[30];
        //print_r('插枪：' . $chaqiang);
        $dianya = $res[31] . $res[32];
        //print_r('电压：' . $dianya);
        $dianliu = $res[33] . $res[34];
        //print_r('电流：' . $dianliu);
        $qiangxianwendu = $res[35];
        //print_r($qiangxianwendu);
        $qiangxianbianma = $res[36] . $res[37] . $res[38] . $res[39] . $res[40] . $res[41] . $res[42] . $res[43];
        //print_r($qiangxianbianma);
        $soc = $res[44];
        //print_r($soc);
        $max_wendu = $res[45];
        //print_r($max_wendu);
        $leiji_time = $res[46] . $res[47];
        //print_r('累计时间：' . $leiji_time);
        $free_time = $res[48] . $res[49];
        //print_r('剩余时间：' . $free_time);
        $dushu = $res[50] . $res[51] . $res[52] . $res[53];
        //print_r('充电度数：' . $dushu);
        $jisundushu = $res[54] . $res[55] . $res[56] . $res[57];
        //print_r($jisundushu);
        $yichong_amount = $res[58] . $res[59] . $res[60] . $res[61];
        //print_r('已充金额：' . $yichong_amount);
        $guzhuang = $res[62] . $res[63];
        //print_r('故障：' . $guzhuang . ' ' . date('Y-m-d H:i:s'));
        //print_r(PHP_EOL);
        //print_r(PHP_EOL);

        $jieguo = json_encode(['out_trade_no' => $out_trade_no, 'device' => $device,
            'qiang' => $qiang, 'status' => $status, 'guiwei' => $guiwei, 'chaqiang' => $chaqiang,
            'dianya' => $dianya, 'dianliu' => $dianliu, 'qiangxianwendu' => $qiangxianwendu,
            'qiangxianbianma' => $qiangxianbianma, 'soc' => $soc, 'max_wendu' => $max_wendu,
            'leiji_time' => $leiji_time, 'free_time' => $free_time, 'dushu' => $dushu, 'jisundushu' => $jisundushu,
            'yichong_amount' => $yichong_amount, 'guzhuang' => $guzhuang
        ]);

        dump($jieguo);
    }


    //处理报文  计划任务
    public function handle_baowen()
    {
        $find = Db::table("dev")->where("id=1274")->find();
        $jieguo = $find['jieguo'];
        $order_no = $find['order_no'];
        $arr = json_decode($jieguo, true);


        $dianya_arr = str_split($arr['dianya'], 2);
        $str_dianya = $dianya_arr[1] . $dianya_arr[0];
        $dianya = hexdec($str_dianya) * 0.1;


        $dianliu_arr = str_split($arr['dianliu'], 2);
        $str_dianliu = $dianliu_arr[1] . $dianliu_arr[0];
        $dianliu = hexdec($str_dianliu) * 0.1;;


        $yichong_amount_arr = str_split($arr['yichong_amount'], 2);
        $str_yichong_amount = $yichong_amount_arr[3] . $yichong_amount_arr[2] . $yichong_amount_arr[1] . $yichong_amount_arr[0];
        $yichong_amount = hexdec($str_yichong_amount) * 0.0001;;

        $dushu_arr = str_split($arr['dushu'], 2);
        $str_dushu = $dushu_arr[3] . $dushu_arr[2] . $dushu_arr[1] . $dushu_arr[0];
        $dushu = hexdec($str_dushu) * 0.0001;

        $leiji_time_arr = str_split($arr['leiji_time'], 2);
        $str_leiji_time = $leiji_time_arr[1] . $leiji_time_arr[0];
        $leiji_time = hexdec($str_leiji_time);

        $order = Db::table("store_yinuo_order")->field("id")->where(['order_no' => $order_no])->find();
        if ($order) {
            Db::table("store_yinuo_order")->where(['order_no' => $order_no])
                ->update([
                    'charging_amount' => $yichong_amount, 'charging_capacity' => $dushu, 'charging_electric' => $dianliu,
                    'charging_voltage' => $dianya, 'charging_duration' => $leiji_time
                ]);
            return $this->api_result(200, '请求成功', [
                'charging_amount' => $yichong_amount, 'charging_capacity' => $dushu, 'charging_electric' => $dianliu,
                'charging_voltage' => $dianya, 'charging_duration' => $leiji_time
            ]);
        } else {
            return $this->api_result(200, '请求成功', [
                'charging_amount' => $yichong_amount, 'charging_capacity' => $dushu, 'charging_electric' => $dianliu,
                'charging_voltage' => $dianya, 'charging_duration' => $leiji_time
            ]);
        }
    }


    //处理结果报文  计划任务
    public function handle_result()
    {
        $str = Db::table("dev")->where("bin_code='3B'")->order("id desc")->value('code');
        //$str = '68a20500003b000000000000017373678087338604862025011317483401983a030305021750460503050217dc4d0300d6060000d6060000740e00007cd404000000000000000000000000001c5b0600000000000000000000000000bce1070000000000000000000000000000000000000000000000d6060000d6060000740e0000000000000000000000000000000000000001504605030502174000000000540a4bd1cd60';
        $arr = str_split($str, 2);

        $out_trade_no = $arr[6] . $arr[7] . $arr[8] . $arr[9] . $arr[10] . $arr[11] . $arr[12]
            . $arr[13] . $arr[14] . $arr[15] . $arr[16] . $arr[17] . $arr[18] . $arr[19] . $arr[20] . $arr[21];

        $order_no = str_replace('0000000000000', '', $out_trade_no);
        $device_sn = $arr[22] . $arr[23] . $arr[24] . $arr[25] . $arr[26] . $arr[27] . $arr[28];
        $qianghao = $arr[29];
        $start_time = $arr[30] . $arr[31] . $arr[32] . $arr[33] . $arr[34] . $arr[35] . $arr[36];
        $end_time = $arr[37] . $arr[38] . $arr[39] . $arr[40] . $arr[41] . $arr[42] . $arr[43];

        $start_time = $this->handle_time($start_time);
        $end_time = $this->handle_time($end_time);

        $jiandanjia = hexdec($arr[47] . $arr[46] . $arr[45] . $arr[44]) * 0.00001; //尖单价
        $jiandianliang = hexdec($arr[51] . $arr[50] . $arr[49] . $arr[48]) * 0.0001; //尖电量
        $jisunjiandianliang = hexdec($arr[55] . $arr[54] . $arr[53] . $arr[52]) * 0.0001; //计损尖电量
        $jianjine = hexdec($arr[59] . $arr[58] . $arr[57] . $arr[56]) * 0.0001; //尖金额

        $fengdanjia = hexdec($arr[63] . $arr[62] . $arr[61] . $arr[60]) * 0.00001;//峰单价
        $fengdianliang = hexdec($arr[67] . $arr[66] . $arr[65] . $arr[64]) * 0.0001; //峰电量
        $jisunfengdianliang = hexdec($arr[71] . $arr[70] . $arr[69] . $arr[68]) * 0.0001; //计损峰电量
        $fengjine = hexdec($arr[75] . $arr[74] . $arr[73] . $arr[72]) * 0.0001; //峰金额

        $pingdanjia = hexdec($arr[79] . $arr[78] . $arr[77] . $arr[76]) * 0.00001;//平单价
        $pingdianliang = hexdec($arr[83] . $arr[82] . $arr[81] . $arr[80]) * 0.0001; //平电量
        $jisunpingdianliang = hexdec($arr[87] . $arr[86] . $arr[85] . $arr[84]) * 0.0001; //计损平电量
        $pingjine = hexdec($arr[91] . $arr[90] . $arr[89] . $arr[88]) * 0.0001; //平金额

        $gudanjia = hexdec($arr[95] . $arr[94] . $arr[93] . $arr[92]) * 0.00001;//谷单价
        $gudianliang = hexdec($arr[99] . $arr[98] . $arr[97] . $arr[96]) * 0.0001; //谷电量
        $jisungudianliang = hexdec($arr[103] . $arr[102] . $arr[101] . $arr[100]) * 0.0001; //计损谷电量
        $gujine = hexdec($arr[107] . $arr[106] . $arr[105] . $arr[104]) * 0.0001; //谷金额

        $dianbiaozongqizhi = hexdec($arr[112] . $arr[111] . $arr[110] . $arr[109] . $arr[108]) * 0.0001;//电表总起值
        $dianbiaozongzhizhi = hexdec($arr[117] . $arr[116] . $arr[115] . $arr[114] . $arr[113]) * 0.0001;//电表总止值

        $zongdianliang = hexdec($arr[121] . $arr[120] . $arr[119] . $arr[118]) * 0.0001; //总电量
        $jisunzongdianliang = hexdec($arr[125] . $arr[124] . $arr[123] . $arr[122]) * 0.0001; //计损总电量

        $amount = hexdec($arr[129] . $arr[128] . $arr[127] . $arr[126]) * 0.0001;;//消费金额

        $jiaoyibiaoshi = $arr[147]; //交易标识  0x01：app 启动 ；0x02：卡启动  ； 0x04：离线卡启动 ； 0x05: vin 码启动充电

        $order_at = $arr[148] . $arr[149] . $arr[150] . $arr[151] . $arr[152] . $arr[153] . $arr[154];
        $order_at = $this->handle_time($order_at);

        $stop_reason = $arr[155];//停止原因

        Db::table("store_yinuo_order")->where(['order_no' => $order_no])
            ->update([
                'device_sn' => $device_sn, 'qianghao' => $qianghao, 'charge_start_time' => $start_time, 'charge_end_time' => $end_time,
                'total_capacity' => $zongdianliang, 'charge_price' => $amount, 'jiaoyibiaoshi' => $jiaoyibiaoshi,
                'stop_reason' => $stop_reason
            ]);
    }

    //处理时间
    public function handle_time($time)
    {
        $arr = str_split($time, 2);

        $year = '20' . hexdec($arr[6]);

        $month = hexdec($arr[5]);
        if ($month < 10) {
            $month = '0' . $month;
        }

        $day = hexdec($arr[4]);
        if ($day < 10) {
            $day = '0' . $day;
        }

        $hour = hexdec($arr[3]);
        if ($hour < 10) {
            $hour = '0' . $hour;
        }

        $min = hexdec($arr[2]);
        if ($min < 10) {
            $min = '0' . $min;
        }

        $sec = hexdec($arr[1] . $arr[0]) * 0.001;
        if ($sec < 10) {
            $sec = '0' . $sec;
        }

        return $year . '-' . $month . '-' . $day . ' ' . $hour . ':' . $min . ':' . $sec;
    }

    //获取手机号
    public function get_phone(Request $request)
    {
        $param = $request->param();

        $code = $param['code'];
        $token = $this->token2();
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
        $data['code'] = $code;
        $result = $this->http_request($url, json_encode($data));

        $str = '';
        if (!empty($result)) {
            if (!empty(json_decode($result))) {
                if (!empty(json_decode($result)->phone_info)) {
                    if (!empty(json_decode($result)->phone_info->phoneNumber)) {
                        $phone = json_decode($result)->phone_info->phoneNumber;
                        if ($phone) {
                            //$id = $_POST['user_id'];
                            //Db::table("store_member")->where("id=$id")->update(["phone" => $phone]);
                            $str = json_encode($phone);
                        }
                    }
                }
            }
        }

        echo $str;
    }


    public function automatic_order()
    {
        $this->automatic_station_rate();
        $this->automatic_qrcode();
        $list = Db::table("store_yinuo_order")->field("id,create_at,status,device_id,park_id")->where(['status' => 1])->select();
        foreach ($list as $k => &$v) {
            $v['time'] = strtotime($v['create_at']);
            $time = time();
            $cha = $time - $v['time'];
            if ($cha > 1800) {
                Db::table("store_yinuo_order")->where(['id' => $v['id']])->update(['status' => 0]);
                Db::table("store_device")->where(['id' => $v['device_id']])->update(['status' => 1]);
                Db::table("store_park")->where(['id' => $v['park_id']])->update(['status' => 1]);
                Db::table("store_device")->where(['park_id' => $v['park_id']])->update(['status' => 1]);
            }
        }
    }

    public function automatic_station_rate()
    {
        $list = Db::table("store_power_station")->where("station_rate=0 or platform_rate=0 or parent_rate=0")->field("id,type,parent_id")->select();
        foreach ($list as $k => &$v) {
            $platform_rate = 10;
            if ($v['type'] == 2) {
                if ($v['parent_id']) {
                    $station_rate = 80;
                    $parent_rate = 10;
                } else {
                    $station_rate = 90;
                    $parent_rate = 0;
                }
            } else {
                $station_rate = 90;
                $parent_rate = 0;
            }
            Db::table("store_power_station")->where(['id' => $v['id']])->update(['station_rate' => $station_rate, 'parent_rate' => $parent_rate, 'platform_rate' => $platform_rate]);
        }

        $list = Db::table("store_power_station")->where("delete_time='null'")->field("id")->select();
        foreach ($list as $k => &$v) {
            Db::table("store_power_station")->where(['id' => $v['id']])->update(['delete_time' => null]);
        }

    }

    public function automatic_qrcode()
    {
        $list = Db::table("store_device")->where("qrcode is null")->limit(5)->select();
        $prefix = 'static/qr_code/';
        foreach ($list as $k => &$v) {
            $url = "https://app.yinuoxinnengyuan.cn/index.php/api/index/device?No=" . $v['sn'];
            $id = $v['id'];
            $image = sysconf('realm_name') . '/static/qr_code/' . 'table_' . $id . '.png';
            Db::query("update store_device set qrcode='$image' where id=$id");
            QrCode::getQrCode('table_' . $id, $id, $prefix, '10', 'L', $url);
        }
    }

    public function automatic_paid()
    {
        $list = Db::table("store_yinuo_order")->field("id,station_id,charging_capacity,device_id")->where("platform_rate=0")->select();
        foreach ($list as $k => &$v) {
            $station = Db::table("store_power_station")->field("platform_rate,parent_rate,parent_id,station_rate")->where(['id' => $v['station_id']])->find();
            $platform_rate = $station['platform_rate'];
            $parent_rate = $station['parent_rate'];
            $parent_id = $station['parent_id'];
            $station_rate = $station['station_rate'];
            Db::table("store_yinuo_order")->where(['id' => $v['id']])->update(['platform_rate' => $platform_rate, 'parent_rate' => $parent_rate, 'parent_id' => $parent_id, 'station_rate' => $station_rate]);
        }
    }

    public function automatic_fenyong()
    {
        $list = Db::table("store_yinuo_order")->field("id,user_id,charging_capacity,device_id,paid_price,charge_price,service_price,electric_price,park_price,end_time,platform_rate,parent_rate,parent_id,station_rate")->where("status in (5,6)")->where("is_fenyong=0 and shuxing='order'")->select();
        $create_at = date('Y-m-d H:i:s');
        $time = time();

        foreach ($list as $k => &$v) {
            $end_time = strtotime($v['end_time']);
            $cha = $time - $end_time;
            if ($cha > 120) {

                //换了 充电费 只属于桩主 不属于平台与上级
                $charge_price = sprintf('%.2f', $v['electric_price'] * $v['platform_rate'] * 0.01);
                $d['charge_price'] = 0;
                $d['service_price'] = sprintf('%.2f', $v['service_price'] * $v['platform_rate'] * 0.01);
                $d['park_price'] = sprintf('%.2f', $v['park_price'] * $v['platform_rate'] * 0.01);
                $d['amount'] = sprintf('%.2f', $d['charge_price'] + $d['service_price'] + $d['park_price']);
                $d['user_id'] = 0;
                $d['create_at'] = $create_at;
                $d['rate'] = $v['platform_rate'];
                $d['order_id'] = $v['id'];
                Db::table("store_fenyong")->insert($d);


                //换了 充电费 只属于桩主 不属于平台与上级
                $charge_price2 = sprintf('%.2f', $v['electric_price'] * $v['parent_rate'] * 0.01);
                $ds['charge_price'] = 0;
                $ds['service_price'] = sprintf('%.2f', $v['service_price'] * $v['parent_rate'] * 0.01);
                $ds['park_price'] = sprintf('%.2f', $v['park_price'] * $v['parent_rate'] * 0.01);
                $ds['amount'] = sprintf('%.2f', $ds['charge_price'] + $ds['service_price'] + $ds['park_price']);
                $ds['user_id'] = $v['parent_id'];
                $ds['create_at'] = $create_at;
                $ds['rate'] = $v['parent_rate'];
                $ds['order_id'] = $v['id'];
                Db::table("store_fenyong")->insert($ds);


                $dd['charge_price'] = sprintf('%.2f', ($v['electric_price'] * $v['station_rate'] * 0.01) + $charge_price + $charge_price2);
                $dd['service_price'] = sprintf('%.2f', $v['service_price'] * $v['station_rate'] * 0.01);
                $dd['park_price'] = sprintf('%.2f', $v['park_price'] * $v['station_rate'] * 0.01);
                $dd['amount'] = sprintf('%.2f', $dd['charge_price'] + $dd['service_price'] + $dd['park_price']);
                $dd['user_id'] = $v['user_id'];
                $dd['create_at'] = $create_at;
                $dd['rate'] = $v['station_rate'];
                $dd['order_id'] = $v['id'];
                Db::table("store_fenyong")->insert($dd);

                Db::table("store_yinuo_order")->where(["id" => $v['id']])->update(['is_fenyong' => 1]);
            }
        }
    }

    public function automatic_device()
    {
        $list = Db::table("store_device")->field("id,cost_model,price,service_price,price2,service_price2,price3,service_price3,price4,service_price4")->select();
        foreach ($list as $k => &$v) {
            $flag = 1;
            if ($v['price'] <= 0) {
                $flag = 0;
            }
            if ($v['price2'] <= 0) {
                $flag = 0;
            }
            if ($v['price3'] <= 0) {
                $flag = 0;
            }
            if ($v['price4'] <= 0) {
                $flag = 0;
            }
            if ($v['service_price'] <= 0) {
                $flag = 0;
            }
            if ($v['service_price2'] <= 0) {
                $flag = 0;
            }
            if ($v['service_price3'] <= 0) {
                $flag = 0;
            }
            if ($v['service_price4'] <= 0) {
                $flag = 0;
            }

            $cost_model = json_decode($v['cost_model'], true);
            foreach ($cost_model as $kk => &$vv) {
                if ($vv == 0) {
                    $flag = 0;
                }
            }
            if ($flag == 0) {
                Db::table("store_device")->where(['id' => $v['id']])->update(['is_shenhe' => 0, 'shenhe_time' => null]);
            } else {
                Db::table("store_device")->where(['id' => $v['id']])->update(['is_shenhe' => 1, 'shenhe_time' => date('Y-m-d H:i:s')]);
            }
        }
    }


    public function automatic_handle_order()
    {
        $list = Db::table("dev")->field("id,out_trade_no,code")->where("bin_code='13' or bin_code='3B' or bin_code='3b'")->where("order_no is null")->where("out_trade_no is not null")->select();
        foreach ($list as $k => &$v) {
            $order_no = str_replace("0000000000000", "", $v['out_trade_no']);
            Db::table("dev")->where(['id' => $v['id']])->update(['order_no' => $order_no]);
        }
    }

    public function automatic_handle_code()
    {
        $list = Db::table("dev")->field("id,code")->where("bin_code='3B' or bin_code='3b'")->where("order_no is not null")->where("jieguo is null or jieguo=''")->select();
        foreach ($list as $k => &$v) {
            $json = $this->handle_code($v['code']);
            Db::table("dev")->where(['id'=>$v['id']])->update(['jieguo'=>$json]);
        }
    }

    public function handle_code($result){
        $res = str_split($result, 2);
        $order_no = $res[6].$res[7].$res[8].$res[9].$res[10].$res[11].$res[12].$res[13].$res[14].$res[15].$res[16].$res[17].$res[18].$res[19].$res[20].$res[21];
        $order_no = str_replace('0000000000000','',$order_no);

        $device_sn = $res[22].$res[23].$res[24].$res[25].$res[26].$res[27].$res[28];

        $start_time = $this->handle_year($res[36]).'-'.$this->handle_month($res[35]).'-'.$this->handle_day($res[34]).' '.$this->handle_hour($res[33]).':'.$this->handle_minute($res[32]).':'.$this->handle_second($res[31].$res[30]);

        $end_time = $this->handle_year($res[43]).'-'.$this->handle_month($res[42]).'-'.$this->handle_day($res[41]).' '.$this->handle_hour($res[40]).':'.$this->handle_minute($res[39]).':'.$this->handle_second($res[38].$res[37]);

        $jian_price = sprintf("%.5f",hexdec($res[47].$res[46].$res[45].$res[44])*0.00001);

        $jian_number = sprintf("%.5f",hexdec($res[51].$res[50].$res[49].$res[48])*0.0001);

        $jian_number2 = sprintf("%.5f",hexdec($res[55].$res[54].$res[53].$res[52])*0.0001);

        $jian_amount = sprintf("%.5f",hexdec($res[59].$res[58].$res[57].$res[56])*0.0001);

        $feng_price = sprintf("%.5f",hexdec($res[63].$res[62].$res[61].$res[60])*0.00001);

        $feng_number = sprintf("%.5f",hexdec($res[67].$res[66].$res[65].$res[64])*0.0001);

        $feng_number2 = sprintf("%.5f",hexdec($res[71].$res[70].$res[69].$res[68])*0.0001);

        $feng_amount = sprintf("%.5f",hexdec($res[75].$res[74].$res[73].$res[72])*0.0001);

        $ping_price = sprintf("%.5f",hexdec($res[79].$res[78].$res[77].$res[76])*0.00001);

        $ping_number = sprintf("%.5f",hexdec($res[83].$res[82].$res[81].$res[80])*0.0001);

        $ping_number2 = sprintf("%.5f",hexdec($res[87].$res[86].$res[85].$res[84])*0.0001);

        $ping_amount = sprintf("%.5f",hexdec($res[91].$res[90].$res[89].$res[88])*0.0001);

        $gu_price = sprintf("%.5f",hexdec($res[95].$res[94].$res[93].$res[92])*0.00001);

        $gu_number = sprintf("%.5f",hexdec($res[99].$res[98].$res[97].$res[96])*0.0001);

        $gu_number2 = sprintf("%.5f",hexdec($res[103].$res[102].$res[101].$res[100])*0.0001);

        $gu_amount = sprintf("%.5f",hexdec($res[107].$res[106].$res[105].$res[104])*0.0001);

        $total_amount_dian = sprintf("%.5f",hexdec($res[121].$res[120].$res[119].$res[118])*0.0001);
        $total_amount_jisun = sprintf("%.5f",hexdec($res[125].$res[124].$res[123].$res[122])*0.0001);

        $total_amount_all = sprintf("%.5f",hexdec($res[129].$res[128].$res[127].$res[126])*0.0001);

        $json = json_encode([
            "order_no"=>$order_no,"device_sn"=>$device_sn,"start_time"=>$start_time,"end_time"=>$end_time,
            "jian_price"=>$jian_price,"jian_number"=>$jian_number,"jian_number2"=>$jian_number2,"jian_amount"=>$jian_amount,
            "feng_price"=>$feng_price,"feng_number"=>$feng_number,"feng_number2"=>$feng_number2,"feng_amount"=>$feng_amount,
            "ping_price"=>$ping_price,"ping_number"=>$ping_number,"ping_number2"=>$ping_number2,"ping_amount"=>$ping_amount,
            "gu_price"=>$gu_price,"gu_number"=>$gu_number,"gu_number2"=>$gu_number2,"gu_amount"=>$gu_amount,
            "total_amount_dian"=>$total_amount_dian,"total_amount_jisun"=>$total_amount_jisun,"total_amount_all"=>$total_amount_all
        ]);


        $device = Db::table("store_device")->where(['sn'=>$device_sn])->find();
        if($device){
            $electric_price = sprintf("%.2f",($jian_number*$device['price'])+($feng_number*$device['price2'])+($ping_number*$device['price3'])+($gu_number*$device['price4']));
            $service_price = sprintf("%.2f",($jian_number*$device['service_price'])+($feng_number*$device['service_price2'])+($ping_number*$device['service_price3'])+($gu_number*$device['service_price4']));

            $charging_amount = sprintf("%.2f",($electric_price+$service_price));

            $second = strtotime($end_time) - strtotime($start_time);
            $charging_duration = (int)ceil($second/60);
            $charging_capacity = $total_amount_dian;

            Db::table("store_yinuo_order")->where(['order_no'=>$order_no])->update(['electric_price'=>$electric_price,'service_price'=>$service_price,'charging_amount' => $charging_amount,'charge_price' => $charging_amount,'charging_duration' => $charging_duration,
                'charging_capacity' => $charging_capacity]);
        }

        return $json;
    }

    public function handle_year($str){
        $year = hexdec($str);
        if ($year <= 9) {
            $year = '0' . $year;
        }
        return '20'.$year;
    }
    public function handle_month($str){
        $month = hexdec($str);
        if ($month <= 9) {
            $month = '0' . $month;
        }
        return $month;
    }
    public function handle_day($str){
        $day = hexdec($str);
        if ($day <= 9) {
            $day = '0' . $day;
        }
        return $day;
    }
    public function handle_hour($str){
        $hour = hexdec($str);
        if ($hour <= 9) {
            $hour = '0' . $hour;
        }
        return $hour;
    }
    public function handle_minute($str){
        $minute = hexdec($str);
        if ($minute <= 9) {
            $minute = '0' . $minute;
        }
        return $minute;
    }
    public function handle_second($str){
        $second = (int)hexdec($str)*0.001;
        if ($second <= 9) {
            $second = '0' . $second;
        }
        return $second;
    }


    public function sms_guzhuang($mobile=18512345769,$id=0){
        if($id==0){
            $id = 0-rand(10000,99999);
        }
        $ishave = Db::table("store_mobile_code2")->where(['mobile'=>$mobile,'type'=>'guzhuang','order_id'=>$id])->find();
        if(empty($ishave)){
            $url = "https://api.guoyangyun.com/api/sms/smsoto.htm?appkey=1121362612202412070944571519586&appsecret=e238c0a5f684da68af56af66c2cfe66f&mobile=$mobile&smsSignId=3ff0685b3d464bd09404862b630e2dd2&templateId=19a76c75ff07475b8601258830396186";
            $res = file_get_contents($url);
            $arr = json_decode($res,true);
            if($arr){
                if($arr['msg']=='成功'){
                    Db::table("store_mobile_code2")->insert(['mobile'=>$mobile,'type'=>'guzhuang','order_id'=>$id,'add_time'=>date('Y-m-d H:i:s')]);
                }
            }
        }
    }

    public function sms_end($mobile=18512345769,$id=0){
        if($id==0){
            $id = 0-rand(10000,99999);
        }
        $ishave = Db::table("store_mobile_code2")->where(['mobile'=>$mobile,'type'=>'end','order_id'=>$id])->find();
        if(empty($ishave)){
            $url = "https://api.guoyangyun.com/api/sms/smsoto.htm?appkey=1121362612202412070944571519586&appsecret=e238c0a5f684da68af56af66c2cfe66f&mobile=$mobile&smsSignId=3ff0685b3d464bd09404862b630e2dd2&templateId=7db1b7444909451792f3c644d7d131b3";
            $res = file_get_contents($url);
            $arr = json_decode($res,true);
            if($arr){
                if($arr['msg']=='成功'){
                    Db::table("store_mobile_code2")->insert(['mobile'=>$mobile,'type'=>'end','order_id'=>$id,'add_time'=>date('Y-m-d H:i:s')]);
                }
            }
        }
    }


    //自动检测机器是否故障或结束
    public function automatic_check_guzhang(){
        $list = Db::table("store_yinuo_order")->field("id,member_id,order_no,create_at,device_id,park_id,dev_status,dev_qiang_status,shuxing,charge_start_time")->where("status=3 and type=1")->select();
        foreach ($list as $k =>&$v){
            $device_sn = Db::table("store_device")->where(['id' => $v['device_id']])->value('sn');
            $ishave = Db::table("dev")->where(['device_sn' => $device_sn,'order_no'=>$v['order_no']])->where("bin_code='3B' or bin_code='3b'")->field("id")->find();
            if($ishave){
                if($v['shuxing']=='order'){
                    Db::table("store_yinuo_order")->where(['id'=>$v['id']])->update(['status'=>4,'remark'=>'定时结束','end_time'=>date('Y-m-d H:i:s'),'charge_end_time'=>date('Y-m-d H:i:s')]);
                }else{
                    Db::table("store_yinuo_order")->where(['id'=>$v['id']])->update(['status'=>5,'remark'=>'定时结束','end_time'=>date('Y-m-d H:i:s'),'charge_end_time'=>date('Y-m-d H:i:s')]);
                    Db::table("store_device")->where(['id' => $v['device_id']])->update(['status' => 1]);
                    Db::table("store_park")->where(['id' => $v['park_id']])->update(['status' => 1]);
                }

                $member_id = $v['member_id'];
                $phone = Db::table("store_member")->where(['id'=>$member_id])->value('phone');
                if($phone){
                    $this->sms_end($phone,$v['id']);
                }

            }else{

                if($v['dev_status']=='离线'){
                    if($v['dev_qiang_status']!='是'){
                        $time = time();
                        if($v['charge_start_time']){
                            $shijian = strtotime($v['charge_start_time']);
                        }else{
                            $shijian = strtotime($v['create_at']);
                        }

                        $cha = $time-$shijian;
                        if($cha>300){
                            if($v['shuxing']=='order'){
                                Db::table("store_yinuo_order")->where(['id'=>$v['id']])->update(['status'=>4,'remark'=>'过时结束','end_time'=>date('Y-m-d H:i:s'),'charge_end_time'=>date('Y-m-d H:i:s')]);
                            }else{
                                Db::table("store_yinuo_order")->where(['id'=>$v['id']])->update(['status'=>5,'remark'=>'过时结束','end_time'=>date('Y-m-d H:i:s'),'charge_end_time'=>date('Y-m-d H:i:s')]);
                            }

                            if ($device_sn) {
                                Db::table("store_device")->where(['id' => $v['device_id']])->update(['status'=>2]);

                                $member_id = $v['member_id'];
                                $phone = Db::table("store_member")->where(['id'=>$member_id])->value('phone');
                                if($phone){
                                    $this->sms_guzhuang($phone,$v['id']);
                                }

                                $start_at = date('Y-m-d H:i:s',time()-300);
                                $end_at = date('Y-m-d H:i:s');
                                $row = Db::table("dev")->field("id")->where(['device_sn' => $device_sn])->where("create_at>='$start_at'")->where("create_at<='$end_at'")->find();
                                if($row) {
                                    $find = Db::table("dev")->where(['device_sn' => $device_sn])->order("id desc")->limit(1)->find();

                                    $connect = $find['connect'];

                                    if($connect){
                                        $baowen = "680D00000098" . $device_sn . "0100358f".$connect.'200358f6666777788889999';
                                        $baowen_res = str_split($baowen, 2);

                                        $answer = '';
                                        foreach ($baowen_res as $kk => &$vv) {
                                            $answer .= chr(intval('0x' . $vv, 16));
                                        }
                                        $buffer = $answer;
                                        $client = stream_socket_client('tcp://localhost:9003');
                                        fwrite($client, $buffer);
                                    }
                                }
                            }
                        }
                    }
                }

            }

        }

    }


    public function automatic_huixian_order()
    {
        $list = Db::table("store_yinuo_order")->field("id,order_no,device_id")->where("status=3 and type=1")->select();
        foreach ($list as $k => &$v) {
            $find = Db::table("dev")->field("id,jieguo")->where("bin_code='13'")->where(['order_no' => $v['order_no']])->order("id desc")->find();

            $have = Db::table("dev")->field("id,jieguo")->where("bin_code='3B' or bin_code='3b'")->where(['order_no' => $v['order_no']])->order("id desc")->find();
            if(empty($have)){
                $device = Db::table("store_device")->where(['id' => $v['device_id']])->find();
                if ($device) {

                    $dev_status = '离线';
                    $dev_qiang_status = '';

                    $charging_voltage = 0;
                    $charging_electric = 0;
                    $charging_amount = 0;
                    $charging_duration = 0;
                    $charging_capacity = 0;
                    if ($find) {
                        $jieguo = $find['jieguo'];
                        if ($jieguo) {
                            $arr = json_decode($jieguo, true);
                            if ($arr) {
                                $dianya = $arr['dianya'];
                                $dianya_arr = str_split($dianya, 2);
                                $charging_voltage = hexdec($dianya_arr[1] . $dianya_arr[0]);

                                $dianliu = $arr['dianliu'];
                                $dianliu_arr = str_split($dianliu, 2);
                                $charging_electric = hexdec($dianliu_arr[1] . $dianliu_arr[0]);

                                $yichong_amount = $arr['yichong_amount'];
                                $yichong_arr = str_split($yichong_amount, 2);
                                $charging_amount = hexdec($yichong_arr[3] . $yichong_arr[2] . $yichong_arr[1] . $yichong_arr[0]);

                                $leiji_time = $arr['leiji_time'];
                                $leiji_arr = str_split($leiji_time, 2);
                                $charging_duration = hexdec($leiji_arr[1] . $leiji_arr[0]);

                                $jisundushu = $arr['jisundushu'];
                                $jisundushu_arr = str_split($jisundushu, 2);
                                $charging_capacity = hexdec($jisundushu_arr[3] . $jisundushu_arr[2] . $jisundushu_arr[1] . $jisundushu_arr[0]);

                                if ($arr['status'] == '00') {
                                    $dev_status = '离线';
                                }
                                if ($arr['status'] == '01') {
                                    $dev_status = '故障';
                                }
                                if ($arr['status'] == '02') {
                                    $dev_status = '空闲';
                                }
                                if ($arr['status'] == '03') {
                                    $dev_status = '充电';
                                }

                                $dev_qiang_status = '';
                                if ($arr['chaqiang'] == '05') {
                                    $dev_qiang_status = '否';
                                }
                                if ($arr['chaqiang'] == '01') {
                                    $dev_qiang_status = '是';
                                }

                            }
                        }
                    }

                    $charging_capacity = sprintf('%.4f', ($charging_capacity * 0.0001));
                    Db::table("store_yinuo_order")->where(["id" => $v['id']])->update([
                        'charging_voltage' => sprintf('%.2f', ($charging_voltage * 0.1)),
                        'charging_electric' => sprintf('%.2f', ($charging_electric * 0.1)),
                        'charging_amount' => sprintf('%.2f', ($charging_amount * 0.0001)),
                        'charge_price' => sprintf('%.2f', ($charging_amount * 0.0001)),

                        'charging_duration' => $charging_duration,
                        'charging_capacity' => $charging_capacity,
                        'dev_status' => $dev_status,
                        'dev_qiang_status' => $dev_qiang_status,
                    ]);
                }

            }else{
                $jieguo = $find['jieguo'];
                if ($jieguo) {
                    $arr = json_decode($jieguo, true);
                    if ($arr) {
                        $charging_amount = $arr['total_amount_all'];
                        $second = strtotime($arr['end_time']) - strtotime($arr['start_time']);
                        $charging_duration = (int)ceil($second/60);
                        $charging_capacity = $arr['total_amount_dian'];
                        Db::table("store_yinuo_order")->where(["id" => $v['id']])->update([
                            'charging_amount' => sprintf('%.2f', ($charging_amount * 0.0001)),
                            'charge_price' => sprintf('%.2f', ($charging_amount * 0.0001)),

                            'charging_duration' => $charging_duration,
                            'charging_capacity' => $charging_capacity,
                        ]);
                    }
                }
            }

        }
    }


    //查到未关闭的订单进行关闭
    public function automatic_end(){
        $list = Db::table("store_yinuo_order")->field("id,order_no,device_id")->where("type=1 and dev_qiang_status='是'")->where("status","in","4,5,6")->where("end_count<30")->select();
        foreach ($list as $k =>&$v){
            $have = Db::table("dev")->where(["order_no"=>$v['order_no']])->where("bin_code='3B' or bin_code='3b'")->find();
            if(empty($have)){
                $device_sn = Db::table("store_device")->where(['id' => $v['device_id']])->value('sn');
                $this->guanbi($device_sn);
                $id = $v['id'];
                Db::query("update store_yinuo_order set end_count=end_count+1 where id=$id");
            }
        }

        $arr = Db::table("store_yinuo_order")->field("id,device_id,park_id")->where("type=1 and shuxing='self'")->where("status=4")->select();
        foreach($arr as $kk =>&$vv){
            $id2 = $vv['id'];
            Db::query("update store_yinuo_order set status=5 where id=$id2");
            Db::table("store_device")->where(['id' => $vv['device_id']])->update(['status' => 1]);
            Db::table("store_park")->where(['id' => $vv['park_id']])->update(['status' => 1]);
        }
    }

    public function guanbi($device_sn){
        $start_at = date('Y-m-d H:i:s',time()-300);
        $end_at = date('Y-m-d H:i:s');
        $row = Db::table("dev")->field("id")->where(['device_sn' => $device_sn])->where("create_at>='$start_at'")->where("create_at<='$end_at'")->find();
        if($row) {
            $find = Db::table("dev")->where(['device_sn' => $device_sn])->where("bin_code='04'||bin_code='13'")->order("id desc")->limit(1)->find();
            if ($find) {

                $connect = $find['connect'];

                $baowen = "680D00000098" . $device_sn . "0100358f".$connect.'200358f6666777788889999';
                $baowen_res = str_split($baowen, 2);

                $answer = '';
                foreach ($baowen_res as $k => &$v) {
                    $answer .= chr(intval('0x' . $v, 16));
                }
                $buffer = $answer;
                $client = stream_socket_client('tcp://localhost:9003');
                fwrite($client, $buffer);
            }
        }
    }


}